package filter;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(filterName = "LoginFilter",urlPatterns = "/*")
public class LoginFilter implements Filter {
    public void destroy() {}
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain
            chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response=(HttpServletResponse) resp;
//情况一：将【登录、注册相关资源】和【静态资源】直接放行
//1.在数组中存储登陆和注册相关的资源路径
        String[] urls = {"/login.jsp", "/register.jsp", "/css/","/images/","/js/",
                "/Login", "/user", "/verifyCode"};
//2.获取当前访问的资源路径
        String uri = request.getRequestURI();
//3.遍历数组，获取到每一个需要放行的资源路径
        for (String u : urls) {
//4.判断当前访问的资源路径字符串是否包含要放行的的资源路径字符串
/*
比如当前访问的资源路径是 /brand-demo/login.jsp
而字符串 /brand-demo/login.jsp 包含了字符串 /login.jsp ，所以就需要放行
*/
            if (uri.contains(u)) {
//找到了，放行
                chain.doFilter(req, resp);
//不再继续向下走了,这里要return
                return;
            }
        }
        HttpSession session = request.getSession();
        Object user = session.getAttribute("LOGIN_USER");
//2. 判断user是否为null
        if (user != null) {
// 已经登录,放行
            chain.doFilter(req, resp);
        } else {
// 没有登陆，存储提示信息，跳转到登录页面
            req.setAttribute("LOGIN_MSG", "您尚未登陆！");
            req.getRequestDispatcher("/login.jsp").forward(req, resp);
        }
    }


    public void init(FilterConfig config) throws ServletException {}
}
